package com.itheima.web;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.HotSetmeal;
import com.itheima.pojo.ReportData;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: dalao
 * @date: 2020/4/14-19:15
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private ReportService reportService;
    @Reference
    private MemberService memberService;

    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {

//        获取当前时间
        DateTime now = new DateTime();
//        创建一个月份的集合
        ArrayList<String> months = new ArrayList<>();
//        向前推12个月
        DateTime dateTime = DateUtil.offsetMonth(now, -12);
        for (int i = 0; i < 12; i++) {
            DateTime time = DateUtil.offsetMonth(dateTime, i);
            months.add(time.toString("yyyy-MM"));
        }
//        获取每个月用户的数量,用集合保存
        List<Integer> memberCount = reportService.getMemberReport(months);
//        封装到map
        Map result = new HashMap<>();
        result.put("months", months);
        result.put("memberCount", memberCount);
        return Result.OK("", result);
    }
    //会员各年龄段人数
    @RequestMapping("/getMemberReportByAge")
    public Result getMemberReportByAge() {
        try {
            List<String> ageList = new ArrayList<>();
            List<Map<String, String>> valueMapList = new ArrayList<>();
            ageList.add("0-17");
            ageList.add("18-30");
            ageList.add("31-60");
            ageList.add("61-");
            int size = ageList.size();
            for (int i = 0; i < size; i++) {
                HashMap<String, String> temp = new HashMap<>();
                String str = ageList.get(i);
                String[] split = str.split("-");
                temp.put("start", split[0]);
                if (split.length == 2) temp.put("end", split[1]);
                int count = memberService.findCountByAge(temp);
                if (split.length < 2) str = str.replace("-", "以上");
                ageList.set(i, str);
                temp.clear();
                temp.put("name", str);
                temp.put("value", count + "");
                valueMapList.add(temp);
            }
            Map<String, Object> resultData = new HashMap<String, Object>(2);
            resultData.put("names", ageList);
            resultData.put("counts", valueMapList);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, resultData);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }
    //会员各性别人数
    @RequestMapping("/getMemberReportBySex")
    public Result getMemberReportBySex() {
        try {
            List<Map<String, String>> valueMapList = new ArrayList<>();
            List<Map> counts = memberService.getCountsBySex();
            List<String> names = new ArrayList<>(3);
            for (Map count : counts) {
                if (count.get("sex").equals("1")) {
                    count.put("sex", "女");
                } else if (count.get("sex").equals("2")) {
                    count.put("sex", "男");
                }
                names.add((String) count.get("sex"));
                Map<String, String> map = new HashMap<>();
                map.put("name", (String) count.get("sex"));
                map.put("value", count.get("num")+"");
                valueMapList.add(map);
            }
            Map<String, Object> resultData = new HashMap<String, Object>(2);
            resultData.put("names", names);
            resultData.put("counts", valueMapList);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, resultData);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
//        调用dubbo服务查询数据
//        穿过的数据是map集合的list
//        map ={name:"",value:""}
//        name=套餐列表名 , value = 预约次数
        List<Map> mapList = reportService.getSetmealReport();
        return Result.OK("", mapList);
    }


    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
//        查询结果用对象接受发送给前端
        ReportData reportData = reportService.getBusinessReportData();
        return Result.OK("", reportData);
    }


    @RequestMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletResponse response, HttpServletRequest request) {
        try {
//            获取报表数据
            ReportData reportData = reportService.getBusinessReportData();
            //1、加载Excel模板,获取template绝对路径
            String realPath = request.getSession().getServletContext().getRealPath("template");
//            拼接文件名
            String templatePath = realPath + "/report_template.xlsx";
//            读取表格文件
            XSSFWorkbook workbook = new XSSFWorkbook(templatePath);
            //2、写Excel
            XSSFSheet sheetAt = workbook.getSheetAt(0);

            sheetAt.getRow(2).getCell(5).setCellValue(reportData.getReportDate());
            sheetAt.getRow(4).getCell(5).setCellValue(reportData.getTodayNewMember());
            sheetAt.getRow(4).getCell(7).setCellValue(reportData.getTotalMember());

            sheetAt.getRow(5).getCell(5).setCellValue(reportData.getThisWeekNewMember());
            sheetAt.getRow(5).getCell(7).setCellValue(reportData.getThisMonthNewMember());

            sheetAt.getRow(7).getCell(5).setCellValue(reportData.getTodayOrderNumber());
            sheetAt.getRow(7).getCell(7).setCellValue(reportData.getTodayVisitsNumber());

            sheetAt.getRow(8).getCell(5).setCellValue(reportData.getThisWeekOrderNumber());
            sheetAt.getRow(8).getCell(7).setCellValue(reportData.getThisWeekVisitsNumber());

            sheetAt.getRow(9).getCell(5).setCellValue(reportData.getThisMonthOrderNumber());
            sheetAt.getRow(9).getCell(7).setCellValue(reportData.getThisMonthVisitsNumber());

            int i = 12;
            List<HotSetmeal> hotSetmeal = reportData.getHotSetmeal();
            for (HotSetmeal setmeal : hotSetmeal) {
                sheetAt.getRow(i).getCell(4).setCellValue(setmeal.getName());
                sheetAt.getRow(i).getCell(5).setCellValue(setmeal.getSetmealCount());
                sheetAt.getRow(i).getCell(6).setCellValue(setmeal.getProportion().doubleValue());
                i++;
            }
            //3、把Excel通过response写回到浏览器
            ServletOutputStream out = response.getOutputStream();
            //告诉浏览器现在返回的是excel
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + java.net.URLEncoder.encode("运营数据报表", "UTF-8") + ".xlsx");
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
